<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    public function getTestPullForGit()
    {
        header('Content-type:text/html;charset=utf-8');
        //以流的方式读取
        $requestBody = file_get_contents("php://input");

        // \Log::info([$requestBody]);

        if (empty($requestBody)) {
            die('send fail');
        }
        $requestBody = json_decode($requestBody,true);

        //加密字符串
        $secret_post = $requestBody['sign'];
        // \Log::info($secret_post);

        //时间戳参数，单位毫秒级
        $time_stamp = $requestBody['timestamp'];

        //在WebHooks签名密钥一栏填写的密钥信息
        $access_token = 'MIIEpAIBAAKCAQEA9AErdwhX8ugD3D73VI9VOW+pjDr1wd2Ug';

        //加密文档
        //https://gitee.com/help/articles/4290
        $secret_join = $time_stamp . "\n" . $access_token;

        $base64 = base64_encode(hash_hmac('sha256', $secret_join, $access_token, true));

        //看推送的是哪个分支就构建哪个分支
        //如有需要可以更改规则，比如屏蔽某些分支不构建
        $branch = str_replace('refs/heads/', '', $requestBody['ref']);

        $requestBody = null;

        // 打开网站目录下的hooks.log文件 需要在服务器上创建 并给写权限
        $fs = fopen('/var/www/laravel-web/storage/logs/deploy_webhooks_pull.log', 'a');

        fwrite($fs, date('Y-m-d H:i:s') . ' ================ Update Start ===============' . PHP_EOL);// 请求ip
        $client_ip = $_SERVER['REMOTE_ADDR'];

        // 把请求的IP和时间写进log
        fwrite($fs, date('Y-m-d H:i:s') . ' Request on [' . date("Y-m-d H:i:s") . '] from [' . $client_ip . ']' . PHP_EOL);

        // 验证token 有错就写进日志并退出
        // if ($base64 !== $secret_post) {
        //     fwrite($fs, date('Y-m-d H:i:s') . " Invalid token [{$client_token}]" . PHP_EOL);

        //     $fs and fclose($fs);

        //     header("HTTP/1.1 404 Not Found");

        //     header("Status: 404 Not Found");

        //     exit;
        // }

        // 如果有需要 可以打开下面，把传送过来的信息写进log 可用于调试，测试成功后注释即可
        // fwrite($fs, 'Data: ' . print_r($data, true) . PHP_EOL);

        // 执行shell命令并把返回信息写进日志
        $output = shell_exec('cd /var/www/laravel-web/;git checkout .; git pull origin ' . $branch . ' 2<&1;');
        fwrite($fs, date('Y-m-d H:i:s') . ' Info:' . print_r($output, true) . PHP_EOL);
        fwrite($fs, date('Y-m-d H:i:s') .  '================ Update End ===============' . PHP_EOL . PHP_EOL);
        $fs and fclose($fs);



        // $output = shell_exec("cd /var/www/laravel-web; sudo -u jybtx git checkout .; git pull origin master 2<&1");
        // \Log::info([$output]);
        // echo "<pre>$output</pre>";
    }

    public function testSend()
    {
        $str = 'gddfdsfsdf';
        \Log::info($str);
    }
}
